//
//  WSMTools.m
//  WinesMall
//
//  Created by Isaac on 17/8/29.
//  Copyright © 2017年 Isaac. All rights reserved.
//

#import "WSMTools.h"
//#import "WSMPayResultController.h"
#import "ISAACLoginController.h"

@implementation WSMTools

+ (WSMTools *)wsmTool {
    static WSMTools *tool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[WSMTools alloc] init];
    });
    return tool;
}

- (NSDateFormatter *)fommatter1 {
    if (_fommatter1 == nil) {
        self.fommatter1 = [[NSDateFormatter alloc]init];
        [_fommatter1 setDateFormat:@"yyyy-MM-dd"];
    }
    return _fommatter1;
}
- (NSDateFormatter *)detailFommatter {
    if (_detailFommatter == nil) {
        self.detailFommatter = [[NSDateFormatter alloc]init];
        [_detailFommatter setDateFormat:@"yyyy-MM-dd HH:mm"];
        
    }
    return _detailFommatter;
}


#pragma mark 时间转换
- (NSString *)getDateTimeByNSNumber:(NSString *)number {///获得年月日
    if (number == nil) {
        return @"暂无时间";
    }
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:number.longLongValue];
    NSString *dateStr = [self.fommatter1 stringFromDate:date];
    return dateStr;
    
}
- (NSString *)getDetailDateTimeByNSNumber:(NSString *)number {///获得具体时间
    if (number.longLongValue == 0) {
        return @"";
    }else {
        NSDate *date = [NSDate dateWithTimeIntervalSince1970:number.longLongValue];
        NSString *dateStr = [self.detailFommatter stringFromDate:date];
        return dateStr;
    }
    
}

- (NSTimeInterval)getTimeFromDate:(NSString *)date {
    
    NSDate *date1 = [self.fommatter1 dateFromString:date];
    NSTimeInterval time;
    if ([date isEqualToString:@"今天"]) {
        time = [[NSDate date] timeIntervalSince1970];
    }else if ([date isEqualToString:@"明天"]) {
        time = [[NSDate date] timeIntervalSince1970] + 3600*24;
    }else {
        time = [date1 timeIntervalSince1970];
    }
    return time;
}



#pragma mark 返回更新时间
- (NSString *)getUpdateTimeByNumber:(NSString *)number {
    
    NSString *timeStr ;
    
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    NSInteger updateTime = time - number.longLongValue ;
    
    if (number.longLongValue == 0) {
        timeStr = [NSString stringWithFormat:@"更新时间暂无"];
    }
    else if (updateTime<60) {
        timeStr = [NSString stringWithFormat:@"更新于%ld秒前",(long)updateTime];
    }
    else if (updateTime<3600) {
        NSInteger min = updateTime/60;
        timeStr = [NSString stringWithFormat:@"更新于%ld分钟前",(long)min];
    }
    else if (updateTime<3600*24) {
        NSInteger hour = updateTime/3600;
        timeStr = [NSString stringWithFormat:@"更新于%ld小时前",(long)hour];
    }
    else if (updateTime<3600*24*30){
        NSInteger day = updateTime/(3600*24);
        timeStr = [NSString stringWithFormat:@"更新于%ld天前",(long)day];
    }
    else if (updateTime<3600*24*365){
        NSInteger month = updateTime/(3600*24*30);
        timeStr = [NSString stringWithFormat:@"更新于%ld个月前",(long)month];
    }
    else {
        NSInteger year = updateTime/(3600*24*365);
        timeStr = [NSString stringWithFormat:@"更新于%ld年前",(long)year];
    }
    
    return timeStr;
    
}

#pragma mark 返回发布时间
- (NSString *)getPublishTimeByNumber:(NSString *)number {
    NSString *timeStr ;
    
    NSTimeInterval time = [[NSDate date] timeIntervalSince1970];
    NSInteger updateTime = time - number.longLongValue ;
    
    if (number.longLongValue == 0) {
        timeStr = [NSString stringWithFormat:@"更新时间暂无"];
    }
    else if (updateTime<60) {
        timeStr = [NSString stringWithFormat:@"%ld秒前 发布",(long)updateTime];
    }
    else if (updateTime<3600) {
        NSInteger min = updateTime/60;
        timeStr = [NSString stringWithFormat:@"%ld分钟前 发布",(long)min];
    }
    else if (updateTime<3600*24) {
        NSInteger hour = updateTime/3600;
        timeStr = [NSString stringWithFormat:@"%ld小时前 发布",(long)hour];
    }
    else if (updateTime<3600*24*30){
        NSInteger day = updateTime/(3600*24);
        timeStr = [NSString stringWithFormat:@"%ld天前 发布",(long)day];
    }
    else if (updateTime<3600*24*365){
        NSInteger month = updateTime/(3600*24*30);
        timeStr = [NSString stringWithFormat:@"%ld个月前 发布",(long)month];
    }
    else {
        NSInteger year = updateTime/(3600*24*365);
        timeStr = [NSString stringWithFormat:@"%ld年前 发布",(long)year];
    }
    
    return timeStr;
}


#pragma mark  跳转到第几个item
- (void)gotoTabBarItemWithTabNum:(NSInteger)num{
    
    AppDelegate * ad = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    
    ad.myTabBar.selectedIndex = num;
    
}

#pragma mark 跳转到登录界面
- (void)pointToLoginPage {
    UIViewController *viewC = [self getCurrentVC];
//    if ([viewC isKindOfClass:[WSMBusinesManagerController class]]) {
//        [viewC dismissViewControllerAnimated:YES completion:^{
//            UIViewController *afterViewC = [self getCurrentVC];
//            ISAACLoginController *loginVC = [[ISAACLoginController alloc]init];
//            UINavigationController *navL = [[UINavigationController alloc]initWithRootViewController:loginVC];
//            [afterViewC presentViewController:navL animated:YES completion:nil];
//            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
//            [userDefaults removeObjectForKey:@"name"];
//            [userDefaults removeObjectForKey:@"password"];
//            [userDefaults removeObjectForKey:@"token"];
//            [userDefaults removeObjectForKey:@"saleStatus"];
//            [userDefaults removeObjectForKey:@"role"];
//            [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
//            return ;
//        }];
//    }
    ISAACLoginController *loginVC = [[ISAACLoginController alloc]init];
    UINavigationController *navL = [[UINavigationController alloc]initWithRootViewController:loginVC];
    [viewC presentViewController:navL animated:YES completion:nil];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults removeObjectForKey:@"name"];
    [userDefaults removeObjectForKey:@"password"];
    [userDefaults removeObjectForKey:@"token"];
    [userDefaults removeObjectForKey:@"saleStatus"];
    [userDefaults removeObjectForKey:@"role"];
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}

#pragma mark 获取当前控制器
- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

#pragma mark ---   版本更新检查
-(void)appVersionChick{
    
    NSMutableDictionary * requestDict = [NSMutableDictionary dictionaryWithDictionary:@{@"type_id":@(2)}];
    
    
    [TTServerTool postDictionaryResult:API_get_version param:requestDict isNeedToken:YES complete:^(BOOL network, TTPublicResult * result, NSError * error) {
        
        if (network) {
            
            if (result) {
                
                if([result.ErrorCode isEqualToString:@"0"]){
                    
                    NSInteger reloadApp = [result.Data[@"updateType"] integerValue];
                    
                    if (reloadApp == 2) {   ////选择更新
                        
                        UIAlertView * alv = [[UIAlertView alloc] initWithTitle:@"发现新版本，是否确定要更新？" message:@"" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
                        alv.tag = 101;
                        [alv show];
                        
                    }else if(reloadApp == 3){   ////强制更新
                        UIAlertView * alv = [[UIAlertView alloc] initWithTitle:@"发现新版本，是否确定要更新？" message:@"" delegate:self cancelButtonTitle:@"立即更新" otherButtonTitles:nil, nil];
                        alv.tag = 100;
                        [alv show];
                    }
                    
                }else{
                    [SVProgressHUD showErrorWithStatus:result.ErrorMsg];
                }
                
            }else{
                [SVProgressHUD showErrorWithStatus:@"暂无数据"];
            }
            
        }else{
            [SVProgressHUD showErrorWithStatus:@"网络错误"];
            //网络链接失败
        }
        
    }];
  
}
#pragma mark -------------- UIAlertViewDelegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if (alertView.tag == 100) {         //强制更新
        //        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:APPUrl]];
        //        exit(0);
        
    }else if(alertView.tag == 101){     //选择更新
        
        if(buttonIndex==1){
//            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:APPUrl]];
        }
    }else if(alertView.tag == 102){     //退出登录
        
    }else if (alertView.tag == 104){
        
        if (buttonIndex == 0) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
        }
        
        
    }
}

#pragma mark 获得设备UUID
-(NSString*)getUUID {
    //    CFUUIDRef puuid = CFUUIDCreate( nil );
    //    CFStringRef uuidString = CFUUIDCreateString( nil, puuid );
    //    NSString * result = (NSString *)CFBridgingRelease(CFStringCreateCopy( NULL, uuidString));
    //    CFRelease(puuid);
    //    CFRelease(uuidString);
    
    NSString *uuid = [[NSUUID UUID] UUIDString];
    return uuid;
}

- (NSString *)getToken {
    
    NSLog(@"%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"token"]);
    if ([[NSUserDefaults standardUserDefaults] objectForKey:@"token"] == nil) {
        return @"";
    }else {
        return [[NSUserDefaults standardUserDefaults] objectForKey:@"token"];
    }
}

#pragma mark 处理拨打电话
- (void)handleCall:(NSString *)phoneNum SuperView:(UIView *)superV {
    if ([TTConfig validateMobile:phoneNum]) {
        NSURL *phoneURL = [NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",phoneNum]];
        UIWebView *phoneCallWebView = [[UIWebView alloc] initWithFrame:CGRectZero];
        [phoneCallWebView loadRequest:[NSURLRequest requestWithURL:phoneURL]];
        [superV addSubview:phoneCallWebView];
    }else {
        [SVProgressHUD showErrorWithStatus:@"电话号码有误"];
    }
}


#pragma mark 获取彩色字符串
- (NSMutableAttributedString *)getAttributedString:(NSString *)oldStr Color:(UIColor*)color begin:(NSInteger)begin end:(NSInteger)end LineSpace:(NSInteger)lineSpace IsCenter:(BOOL)isCenter Font:(NSInteger)font{
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:oldStr];
    
    [attributeStr addAttributes:@{NSForegroundColorAttributeName:color,NSFontAttributeName:[UIFont systemFontOfSize:font]} range:NSMakeRange(begin, end)];
    
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc]init];
    [paragraphStyle setLineSpacing:lineSpace];//行距的大小
    if (isCenter == YES) {
        [paragraphStyle setAlignment:NSTextAlignmentCenter];
    }
    [attributeStr addAttribute:NSParagraphStyleAttributeName value:paragraphStyle range:NSMakeRange(0, oldStr.length)];
    
    return attributeStr;
}



#pragma 选择其他方式后删除单例里面的数据
- (void)deleteAliPayDataForDanli {
//    [TTManagerDataCenter shareManegerData].isAliPayOrWeiXin = @"";
//    [TTManagerDataCenter shareManegerData].payType = 0;
//    [TTManagerDataCenter shareManegerData].bankModel = nil;
}

@end
